package tech.mhuang.hmtool.core.sample.io;

import tech.mhuang.core.file.FileUtil;
import tech.mhuang.core.io.IOUtil;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * io测试工具类
 *
 * @author mhuang
 * @since 1.0.0
 */
public class TestIO {
    public static void main(String[] args) {
        File file = new File("ssa.txt");
        try {
            FileUtil.createFile(file);
            //数据写入
            OutputStream out = FileUtil.openOutputStream(file);
            IOUtil.write("你好", out);
            IOUtil.write("世界".getBytes(), out);
            IOUtil.close(out);

            //输入流转换
            //输入转String、采用默认系统编码、自动关闭流
            InputStream in = FileUtil.openInputStream(file);
            System.out.println(IOUtil.toString(in));
            //输入转String、采用指定的utf8编码、自动关闭流
            in = FileUtil.openInputStream(file);
            System.out.println(IOUtil.toString(in, "utf8"));
            //输入转string、采用指定的utf8编码、设置不关闭流
            in = FileUtil.openInputStream(file);
            System.out.println(IOUtil.toString(in, "utf8", false));
            IOUtil.close(in);
            //输入转byte数组、自动关闭流
            in = FileUtil.openInputStream(file);
            System.out.println(IOUtil.toByteArray(in));
            //输入转byte数组、不自动关闭流
            in = FileUtil.openInputStream(file);
            System.out.println(IOUtil.toByteArray(in, false));
            IOUtil.close(in);

            //拷贝
            File copyFile = new File("a.txt");
            FileUtil.createFile(copyFile);
            in = FileUtil.openInputStream(file);
            IOUtil.copy(in, FileUtil.openOutputStream(copyFile));
            System.out.println("打印copy得数据" + FileUtil.readFileToString(copyFile));
            IOUtil.close(in);

            //关闭资源、支持单个、多个关闭、关闭得资源需继承Closeable接口、比如InputStream、Outpusteam、Writer等等
            in = FileUtil.openInputStream(file);
            IOUtil.close(in);
            out = FileUtil.openOutputStream(file);
            IOUtil.close(out);
            in = FileUtil.openInputStream(file);
            out = FileUtil.openOutputStream(file);
            IOUtil.close(in, out);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
